package com.gdit.zax.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gdit.zax.Constant;
import com.gdit.zax.dao.SignDao;
import com.gdit.zax.dao.UserDao;
import com.gdit.zax.factory.DAOFactory;
import com.gdit.zax.utils.DBUtil;
import com.gdit.zax.utils.O;
import com.gdit.zax.utils.TextUtil;
import com.gdit.zax.utils.VeriFicUtil;

public class Signin extends HttpServlet {
	//http://pingkgs3pc:8080/zuiaixue/signin?accesstoken=642e159d1e74bdf1ea277b94b99960f790e436342d4cb9c1
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String accesstoken = request.getParameter("accesstoken");
		//检测参数
		if (TextUtil.isEmpty(accesstoken)) {
			O.printFail(response, 1, "请检查accesstoken参数!");
			return;
		}
		
		int uid = VeriFicUtil.getVFID(accesstoken);
		Connection conn = DBUtil.getConnection();
		
		if (uid == Integer.MIN_VALUE || uid == Integer.MAX_VALUE) {
			O.printNoLogin(response);
			return;
		}
		
		if (conn==null) {
			O.printFail(response, 1000, "数据库连接失败!");
			return;
		}
		
		
		DAOFactory dao  = DAOFactory.init(conn, request, response);
		UserDao udao =dao.getUserDao();
		SignDao sdao = dao.getSignDao();
		
		if (sdao.signin(uid)){
			if (udao.addscore(uid, Constant.SCORE_SIGNIN)) {
				O.printSuccess(response, "签到成功!");
			} else {
				O.printFail(response, 1, "签到失败，增加积分时出错，请联系管理员!");
			}
		} else {
			O.printFail(response, 1, "今日已签到，请改天再来吧!");
		}
		
	}

}
